package com.ocelot.san.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.commons.lang.StringUtils;

import com.ocelot.san.dto.Notary;
import com.ocelot.san.form.NotaryForm;
import com.ocelot.san.service.NotaryService;


@ManagedBean(name = "notaryController")
@ViewScoped
public class NotaryController {

	private NotaryForm notaryForm;
	
	@ManagedProperty(value = "#{notaryService}")
	private NotaryService notaryService;
	
	@PostConstruct
	public void init() {
		notaryForm = new NotaryForm();
		notaryForm.setEditNotary(new Notary());
		refreshNotaryList();
	}
	
	
	public void submitNotary(ActionEvent event) {
		if (validateForm()) {
			notaryService.save(notaryForm.getEditNotary());
			// clear Data
			notaryForm.setEditNotary(new Notary());
			refreshNotaryList();
		}
	}
	
	

	protected void refreshNotaryList() {
		notaryForm.setNotaries(notaryService.fetchAll());
	}
	
	public boolean validateForm() {
		List<String> errors = new ArrayList<String>();
		
		if(StringUtils.isEmpty(notaryForm.getEditNotary().getName())) {
			errors.add("La Descripción es requerida");
		}
		
		if(errors.size() > 0) {
			for(String error:errors){
				 FacesMessage message=new FacesMessage(error);  
				 message.setSeverity(FacesMessage.SEVERITY_INFO);  
				 FacesContext ctx= FacesContext.getCurrentInstance();  
				 ctx.addMessage("notaryForm", message);
			}
			return false;
		}
		return true;
	}

	
	public String editItem() {
		Long idToEdit = notaryForm.getToEdit();
		Notary toModify = getNotaryById(idToEdit);
		notaryForm.setEditNotary(toModify);
		return null;
	}

	public String removeItem() {
		Long indexToRemove = notaryForm.getToRemove();
		Notary removeItem = getNotaryById(indexToRemove);
		if (removeItem != null) {
			notaryService.delete(removeItem.getId());
			notaryForm.getNotaries().remove(removeItem);
			notaryForm.setEditNotary(new Notary());
			refreshNotaryList();
		}
		return null;
	}
	
	protected Notary getNotaryById(Long id){
		return notaryService.findById(id);
	}


	public NotaryForm getNotaryForm() {
		return notaryForm;
	}


	public void setNotaryForm(NotaryForm notaryForm) {
		this.notaryForm = notaryForm;
	}


	public NotaryService getNotaryService() {
		return notaryService;
	}


	public void setNotaryService(NotaryService notaryService) {
		this.notaryService = notaryService;
	}

	
}
